import json
from fastapi import HTTPException, Request, Depends
from fastapi.security import SecurityScopes
from package.fastapi.security import permission, security_jwt


async def get_current_user(request: Request = None, token=Depends(permission.oauth2_scheme)):
    """获取登陆用户"""
    return None

    if apikey := request.headers.get('X-API-KEY'):
        if permission.check_apikey(apikey):
            request.state.user = None
            return
        raise HTTPException(401, detail='无效apikey')

    try:
        payload = security_jwt.decode_token(token)
        key = payload['key']
        user = permission.get_user(key)
        if not user:
            raise HTTPException(401, detail='凭据已失效')

        user = json.loads(user.decode())
        request.state.user = user
        return user
    except Exception:
        raise HTTPException(status_code=401, detail='无效凭据')


async def get_user_funcable(user=Depends(get_current_user), scopes: SecurityScopes = None,
                            request: Request = None):
    """用户定义的权限 对比"""
    if user is None:
        return user

    scopes_func = set(scopes.scopes)
    if not scopes_func:
        return user

    for role in user['roles']:  # 管理员可以看所有数据
        if role['name'] == 'Administrator':
            return user

    for role in user['roles']:  # 多个角色取并集 其中一个角色可访问即可访问该功能
        mod_scopes = set([f'{module["module"]}:{scope["func"]}' for module in role.get('permit', {})
                          for scope in module.get('scopes', []) if scope.get('enabled')])
        if scopes_func.intersection(mod_scopes):  # 用户可访问
            break
    else:
        raise HTTPException(status_code=403, detail='用户权限不足')
    return user
